package com.youtills.view;

import com.youtills.core.lang.StringUtil;
import com.youtills.resource.HtmlLayoutResponse;
import com.youtills.resource.HtmlResponse;
import com.youtills.resource.HttpResourceController;
import com.youtills.resource.HttpResponse;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * TODO - !!!doc me!!!
 *
 * @author ravi.chiluveru
 * @since 23.0 (7/28/14)
 */
public class HtmlResponseWriter implements HttpResponseWriter {

    private final HttpResourceController controller;

    public HtmlResponseWriter(HttpResourceController controller) {
        this.controller = controller;
    }

    public void writeResponse(){

        final HttpResponse response = this.controller.execute();
        final HttpServletResponse httpServletResponse = controller.getResponse();

        if(response != null) {
            if (response.getCookies() != null) {
                for (Cookie cookie : response.getCookies()) {
                    httpServletResponse.addCookie(cookie);
                }
            }
            httpServletResponse.setStatus(response.getStatus());
        }

        controller.getRequest().setAttribute("controller", controller);

        if(controller instanceof HtmlLayoutResponse) {
            if(dispatch(((HtmlLayoutResponse)controller).getLayoutPage())) {
                return;
            }
        }

        if(controller instanceof HtmlResponse) {
            if(dispatch(((HtmlResponse)controller).getContentPage())) {
                return;
            }
        }
    }

    private boolean dispatch(String page ) {
        if(!StringUtil.isEmpty(page)){
            try {
                controller.getRequest().getRequestDispatcher(page).forward(controller.getRequest(), controller.getResponse());
                return true;
            } catch (ServletException | IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}
